package com.bodacn.storagescan;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;

import butterknife.BindView;
import butterknife.OnClick;

public class NoSewActivity extends AppCompatActivity {
    @BindView(R.id.edit_Barcode)
    EditText edit_Barcode;
    @BindView(R.id.edt_PlaceNo)
    EditText edt_PlaceNo;
    @BindView(R.id.edt_HighCar2)
    EditText edt_HighCar2;
    @BindView(R.id.edt_OrderNo)
    EditText edt_OrderNo;
    @BindView(R.id.edt_StyleNo)
    EditText edt_StyleNo;
    @BindView(R.id.edt_DBH)
    EditText edt_DBH;
    @BindView(R.id.edt_PO)
    EditText edt_PO;
    @BindView(R.id.edt_StyleSort)
    EditText edt_StyleSort;
    @BindView(R.id.edt_HighCar)
    EditText edt_HighCar;
    @BindView(R.id.tv_ResultInfo)
    EditText tv_ResultInfo;
    @BindView(R.id.txt_titleInv)
    TextView txt_titleInv;
    @BindView(R.id.btn_HighCarBind)
    Button btn_HighCarBind;
    @BindView(R.id.btn_HighPutIn)
    Button btn_HighPutIn;
    @BindView(R.id.btn_HighQuery)
    Button btn_HighQuery;
    @BindView(R.id.btn_HighSend)
    Button btn_HighSend;
    @BindView(R.id.PutIn_liner)
    LinearLayout PutIn_liner;
    @BindView(R.id.BindA_liner)
    LinearLayout BindA_liner;
    @BindView(R.id.BindA_HorScroll)
    LinearLayout BindA_HorScroll;
    @BindView(R.id.list_Order)
    ListView list_Order;

    @BindView(R.id.listQuery)
    ListView listQuery;

    private String TAG = this.getClass().getName();
    private final static int MSG_AllowScan=9000;
    private final static int MSG_ScanBarcodeOver=9001;
    private final static int MSG_Detail =9002;
    private final static int MSG_QueryDetail =9003;

    private final static int MSG_Error=9004;
    boolean ScanSign=false;
    JSONArray returnJson,detailJSON, queryJSON;
    String curLoginUserNo,curLoginUser,curLoginTime;//操作员所属部门等信息;
    String FormType="",Caption="",PrBarcode="",FuncName="Bind";
    //拦截扫描枪输入部分
    String BarcodeStr="";
    ReentrantLock reentrantLock = new ReentrantLock();
    ScannerManager scannerManager;
    String BatchID= UUID.randomUUID().toString().toUpperCase();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nosew);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curLoginTime=paramBundle.getString("LoginTime");

        FormType=paramBundle.getString("FormType");
        Caption=paramBundle.getString("Caption");
        //置标题颜色
        //界面变量
        ((TextView)findViewById(R.id.tv_userName)).setText("用户:"+curLoginUser);
        txt_titleInv.setText(Caption);
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code,String deviceName) {
                Log.d(TAG, "code= " + code);
                playRingtone();
                tv_ResultInfo.setText(code);
                edit_Barcode.setText(code);
                ScanBarcode(edit_Barcode.getText().toString(),BatchID);
            }
        },this);
    }


    //登陆校验;
    private void ScanBarcode(String paramBarcode,String paramBatchID){
        hideIM(edit_Barcode);
        if (ScanSign==false) {
            if (FuncName.equals("Query")){
                //刷新表格
                try {
                    QueryGridAdapter queryGridAdapter = new QueryGridAdapter(getApplicationContext());
                    queryGridAdapter.jsonArray = new JSONArray("[]");
                    listQuery.setAdapter(queryGridAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            ScanSign=true;
            //组织WebService地址;
            edit_Barcode.setEnabled(false);
            edit_Barcode.setText("");
            String SqlComm = "Exec Storage_NoSew_ScanBarcode @Barcode='" + paramBarcode
                    + "',@FormType='" + FormType+"-"+FuncName+ "',@BatchID='"+paramBatchID
                    + "',@PrOrderNo='" + edt_OrderNo.getText().toString()
                    + "',@PrStyleNo='" + edt_StyleNo.getText().toString()
                    + "',@Prdbh='" + edt_DBH.getText().toString()
                    + "',@Prpo='" + edt_PO.getText().toString()
                    + "',@PrStyleSort='" + edt_StyleSort.getText().toString()
                    + "',@PrPlaceNo='" + edt_PlaceNo.getText().toString()
                    + "',@HighCar='" + edt_HighCar.getText().toString()
                    + "',@HighCar2='" + edt_HighCar2.getText().toString()
                    + "',@OperType='ScanBarcode',@UserNo='" + curLoginUserNo
                    + "',@UserName='" + curLoginUser+ "'";
            PrBarcode = paramBarcode;
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } else Toast.makeText(this,"请稍等或退出重进!",Toast.LENGTH_LONG).show();
    }



    //登陆校验;
    private void ScanDetail(String paramBatchID){
        hideIM(edit_Barcode);
        if (ScanSign==false) {
            ScanSign=true;
            //组织WebService地址;
            edit_Barcode.setEnabled(false);
            edit_Barcode.setText("");
            String SqlComm = "Exec Storage_NoSew_ScanBarcode @Barcode='" + PrBarcode
                    + "',@FormType='" + FormType+"-"+FuncName+ "',@BatchID='"+paramBatchID
                    + "',@PrOrderNo='" + edt_OrderNo.getText().toString()
                    + "',@PrStyleNo='" + edt_StyleNo.getText().toString()
                    + "',@Prdbh='" + edt_DBH.getText().toString()
                    + "',@Prpo='" + edt_PO.getText().toString()
                    + "',@PrStyleSort='" + edt_StyleSort.getText().toString()
                    + "',@PrPlaceNo='" + edt_PlaceNo.getText().toString()
                    + "',@HighCar='" + edt_HighCar.getText().toString()
                    + "',@HighCar2='" + edt_HighCar2.getText().toString()
                    + "',@OperType='GetDetail',@UserNo='" + curLoginUserNo
                    + "',@UserName='" + curLoginUser+ "'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } else Toast.makeText(this,"请稍等或退出重进!",Toast.LENGTH_LONG).show();
    }
    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @OnClick({R.id.btn_HighCarBind, R.id.btn_HighPutIn, R.id.btn_HighQuery,R.id.btn_HighSend})
    public void onClick(View view){
        BindA_liner.setVisibility(View.GONE);
        BindA_HorScroll.setVisibility(View.GONE);
        PutIn_liner.setVisibility(View.GONE);
        listQuery.setVisibility(View.GONE);
        btn_HighCarBind.setBackground(getResources().getDrawable(R.drawable.btn_color_gray));
        btn_HighPutIn.setBackground(getResources().getDrawable(R.drawable.btn_color_gray));
        btn_HighQuery.setBackground(getResources().getDrawable(R.drawable.btn_color_gray));
        btn_HighSend.setBackground(getResources().getDrawable(R.drawable.btn_color_gray));
        view.setBackground(getResources().getDrawable(R.drawable.btn_color_green));
        switch (view.getId()){
            case R.id.btn_HighCarBind:
                BindA_liner.setVisibility(View.VISIBLE);
                BindA_HorScroll.setVisibility(View.VISIBLE);
                FuncName="Bind";
                break;
            case R.id.btn_HighPutIn:
                FuncName="PutIn";
                break;
            case R.id.btn_HighSend:
                FuncName="Send";
                PutIn_liner.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_HighQuery:
                FuncName="Query";
                listQuery.setVisibility(View.VISIBLE);
                break;

        }

    }



    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            hideIM(edit_Barcode);
            edit_Barcode.setEnabled(true);
            edit_Barcode.selectAll();
            edit_Barcode.requestFocus();
            ScanSign=false;
            switch (msgId) {
                case MSG_Detail:
                    if (detailJSON!=null) {
                        DetailGridAdapter detailGridAdapter = new DetailGridAdapter(getApplicationContext());
                        detailGridAdapter.jsonArray = detailJSON;
                        list_Order.setAdapter(detailGridAdapter);
                    }
                    break;
                case MSG_QueryDetail:
                    if (queryJSON!=null) {
                        QueryGridAdapter queryGridAdapter = new QueryGridAdapter(getApplicationContext());
                        queryGridAdapter.jsonArray = queryJSON;
                        listQuery.setAdapter(queryGridAdapter);
                    }
                    break;
                case MSG_Error:
                    Bundle bundle=msg.getData();
                    AlertDialog alertDialog = new AlertDialog.Builder(edt_DBH.getContext())
                            .setTitle(getString(R.string.SystemHint)).setMessage(bundle.getString("Hint"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideIM(edit_Barcode);
                                    edit_Barcode.selectAll();
                                    edit_Barcode.requestFocus();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                    break;
                case MSG_ScanBarcodeOver:
                    if (returnJson!=null) {
                        //填充屏幕
                        fillScreen(returnJson.optJSONObject(0));
                    }
                    break;
                case MSG_AllowScan:
                    ScanSign=false;
                    break;
                default:
                    break;
            }
        }
    };


    private void fillScreen(JSONObject optJSONObject) {
        if (optJSONObject!=null){
            try {
                if (optJSONObject.has("BatchID")) BatchID=optJSONObject.getString("BatchID");
                if (optJSONObject.has("PlaceNo")) edt_PlaceNo.setText(optJSONObject.getString("PlaceNo"));
                if (optJSONObject.has("HighCar")) {
                    edt_HighCar2.setText(optJSONObject.getString("HighCar"));
                    edt_HighCar.setText(optJSONObject.getString("HighCar"));
                }
                if (optJSONObject.has("OrderNo")) edt_OrderNo.setText(optJSONObject.getString("OrderNo"));
                if (optJSONObject.has("StyleNo")) edt_StyleNo.setText(optJSONObject.getString("StyleNo"));
                if (optJSONObject.has("DBH")) edt_DBH.setText(optJSONObject.getString("DBH"));
                if (optJSONObject.has("PO")) edt_PO.setText(optJSONObject.getString("PO"));
                if (optJSONObject.has("StyleSort")) edt_StyleSort.setText(optJSONObject.getString("StyleSort"));

                if (optJSONObject.has("ResultInfo")) tv_ResultInfo.setText(optJSONObject.getString("ResultInfo"));
                if (optJSONObject.has("ErrInfo") == true) {
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle(getString(R.string.SystemHint)).setMessage(optJSONObject.getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideIM(edit_Barcode);
                                    edit_Barcode.selectAll();
                                    edit_Barcode.requestFocus();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                if (optJSONObject.has("GetDetail")){
                    if (optJSONObject.getString("GetDetail").equals("Y")){
                        ScanDetail(BatchID);
                    }
                }
                if (optJSONObject.has("ClearDetail")){
                    if (optJSONObject.getString("ClearDetail").equals("Y")) {
                        //刷新表格
                        DetailGridAdapter detailGridAdapter = new DetailGridAdapter(getApplicationContext());
                        detailGridAdapter.jsonArray = new JSONArray("[]");
                        list_Order.setAdapter(detailGridAdapter);
                    };
                }
                if (optJSONObject.has("ClearQueryDetail")){
                    if (optJSONObject.getString("ClearQueryDetail").equals("Y")) {
                        //刷新表格
                        QueryGridAdapter queryGridAdapter = new QueryGridAdapter(getApplicationContext());
                        queryGridAdapter.jsonArray = new JSONArray("[]");
                        listQuery.setAdapter(queryGridAdapter);
                    };
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //订单表格适配器;
    public final class DetailGridAdapter extends BaseAdapter {

        private LayoutInflater inflater;
        public DetailGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        private JSONArray jsonArray;

        @Override
        public int getCount() {
            return jsonArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return jsonArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.activity_nosew_item, null, false);
            String tmpValue;
            int backcolor=getResources().getColor(R.color.white);
            int fontcolor=getResources().getColor(R.color.text_black);
            try {
                if (jsonArray.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = jsonArray.optJSONObject(position).getString("ConColor");
                    backcolor=GetColorValue(tmpValue);
                }
                if (jsonArray.optJSONObject(position).has("ConFontColor")==true) {
                    tmpValue = jsonArray.optJSONObject(position).getString("ConFontColor");
                    fontcolor=GetColorValue(tmpValue);
                }
                TextView tv = convertView.findViewById(R.id.tv_PartName);// 显示文字
                if (jsonArray.optJSONObject(position).has("PartName")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("PartName"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_Number);// 显示文字
                if (jsonArray.optJSONObject(position).has("Number")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("Number"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_PackNum);// 显示文字
                if (jsonArray.optJSONObject(position).has("PackNum")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("PackNum"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_InCarNum);// 显示文字
                if (jsonArray.optJSONObject(position).has("InCarNum")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("InCarNum"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_InCarPack);// 显示文字
                if (jsonArray.optJSONObject(position).has("InCarPack")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("InCarPack"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_StyleSort);// 显示文字
                if (jsonArray.optJSONObject(position).has("StyleSort")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("StyleSort"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_TxmType);// 显示文字
                if (jsonArray.optJSONObject(position).has("TxmType")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("TxmType"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }



    }



    //订单表格适配器;
    public final class QueryGridAdapter extends BaseAdapter {

        private LayoutInflater inflater;
        public QueryGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        private JSONArray jsonArray;

        @Override
        public int getCount() {
            return jsonArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return jsonArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.activity_nosew_queryitem, null, false);
            String tmpValue;
            int backcolor=getResources().getColor(R.color.white);
            int fontcolor=getResources().getColor(R.color.text_black);
            try {
                if (jsonArray.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = jsonArray.optJSONObject(position).getString("ConColor");
                    backcolor=GetColorValue(tmpValue);
                }
                if (jsonArray.optJSONObject(position).has("ConFontColor")==true) {
                    tmpValue = jsonArray.optJSONObject(position).getString("ConFontColor");
                    fontcolor=GetColorValue(tmpValue);
                }
                TextView tv = convertView.findViewById(R.id.tv_HighCar);// 显示文字
                if (jsonArray.optJSONObject(position).has("HighCar")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("HighCar"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_OrderNo);// 显示文字
                if (jsonArray.optJSONObject(position).has("OrderNo")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("OrderNo"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_StyleNo);// 显示文字
                if (jsonArray.optJSONObject(position).has("StyleNo")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("StyleNo"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_StyleSort);// 显示文字
                if (jsonArray.optJSONObject(position).has("StyleSort")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("StyleSort"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_PO);// 显示文字
                if (jsonArray.optJSONObject(position).has("PO")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("PO"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_Color);// 显示文字
                if (jsonArray.optJSONObject(position).has("Color")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("Color"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_ColorNo);// 显示文字
                if (jsonArray.optJSONObject(position).has("ColorNo")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("ColorNo"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_PSXX);// 显示文字
                if (jsonArray.optJSONObject(position).has("PSXX")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("PSXX"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_Size);// 显示文字
                if (jsonArray.optJSONObject(position).has("Size")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("Size"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_Number);// 显示文字
                if (jsonArray.optJSONObject(position).has("Number")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("Number"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_PackNum);// 显示文字
                if (jsonArray.optJSONObject(position).has("PackNum")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("PackNum"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);
                tv = convertView.findViewById(R.id.tv_Status);// 显示文字
                if (jsonArray.optJSONObject(position).has("Status")==true) {
                    tv.setText(jsonArray.optJSONObject(position).getString("Status"));
                }
                tv.setTextColor(fontcolor);
                tv.setBackgroundColor(backcolor);

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }



    }


    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }


    //判断是否为数字，不然不转
    public static boolean isNumer(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }



    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        ScanSign=true;
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public  synchronized void run() {
                try{
                    reentrantLock.lock();
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    ScanSign=false;
                    String OperType="";
                    if (jsonArray!=null&&jsonArray.length()>0) {
                        if (jsonArray.optJSONObject(0).has("OperType"))
                            OperType = jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE"))
                            OperType = jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (OperType.equals("ScanBarcode") == true) {
                            returnJson = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ScanBarcodeOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OperType.equals("GetDetail") == true) {
                            detailJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_Detail;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OperType.equals("QueryDetial") == true) {
                            queryJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_QueryDetail;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OperType.equals("SQLExcept") == true) {
                            Message msg = new Message();
                            msg.what = MSG_Error;
                            Bundle bundle=new Bundle();
                            bundle.putString("Hint",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                    }  else {
                        Message msg = new Message();
                        msg.what = MSG_Error;
                        Bundle bundle=new Bundle();
                        bundle.putString("Hint","未返回任何数据!");
                        msg.setData(bundle);
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //刷新界面;
                    ScanSign=false;
                    Message msg = new Message();
                    msg.what = MSG_Error;
                    Bundle bundle=new Bundle();
                    bundle.putString("Hint",e.getMessage());
                    msg.setData(bundle);
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                    reentrantLock.unlock();
                }finally {
                    reentrantLock.unlock();
                }

            }

        };
        new Thread(run).start();

    }
}
